import itertools
from typing import List

# 计算所有可能的算式
FORMULA = []
for marks in itertools.product(["+", "-", "*", "/"], repeat=3):
    for bracket in ["{0}%s{1}%s{2}%s{3}", "({0}%s{1})%s{2}%s{3}", "({0}%s{1}%s{2})%s{3}", "{0}%s({1}%s{2})%s{3}",
                    "{0}%s({1}%s{2}%s{3})", "({0}%s{1})%s({2}%s{3})", "{0}%s{1}%s({2}%s{3})"]:
        FORMULA.append((bracket % marks))


class Solution:
    def judgePoint24(self, nums: List[int]) -> bool:
        for card_order in set(itertools.permutations(nums, 4)):  # 遍历所有可能的卡牌顺序（最多24种可能）
            for formula in FORMULA:  # 遍历所有可能的算式（448种可能）
                final_formula = formula.format(*card_order)
                try:
                    if round(eval(final_formula), 3) == 24:
                        return True
                except ZeroDivisionError:
                    continue
        return False


if __name__ == "__main__":
    print(Solution().judgePoint24([4, 1, 8, 7]))  # True
    print(Solution().judgePoint24([1, 2, 1, 2]))  # False
